<?php

namespace App\Http\Controllers;

use App\Models\Car;
use App\Models\Member;
use App\Models\MyCar;
use App\Models\MyStage;
use App\Models\Parking;
use App\Models\Record;
use App\Models\Stage;
use App\Repos\CarRepo;
use App\Repos\MemberRepo;
use App\Repos\MessageRepo;
use App\Services\StopCar;
use App\Transformers\CarTransformer;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class CarController extends ApiController
{
    protected $stopCarService;
    
    public function __construct(StopCar $stopCar)
    {
        parent::__construct();
        $this->stopCarService = $stopCar;
    }
    
    public function index($user_id=0)
    {
        if($user_id){
            $this->user = Member::find($user_id);
        }
        $parking=null;
        if($this->request->has('parking_id')){
            $parking_id = $this->request->input('parking_id');
            $parking = Parking::findOrFail($parking_id);
            $list = (new CarRepo())->setTempParking($parking)->myCars($this->user);
            return $this->success($list);
        }
        
        $list = (new CarRepo())->myCars($this->user);
        return $this->success($list);
        
    }
    
    //停入车位
    public function stopCar()
    {
        $car_id=$this->request->car_id;
        $parking_id=$this->request->parking_id;
        
        if(!$myCar = MyCar::find($car_id)){
            return $this->error(1,'车与当前用户信息不对应');
        }
        
        $car = Car::findOrFail($myCar->CarID);//停哪辆车
        
        $parking = Parking::findOrFail($parking_id);//停到哪个车位
        
        $to_user = Member::findOrFail($parking->user_id);//车位是谁的
        
        //声明对象准备停车
        $this->stopCarService->user = $this->user;
        $this->stopCarService->car = $car;
        $this->stopCarService->to_user = $to_user;
        $this->stopCarService->parking = $parking;
        $this->stopCarService->myCar = $myCar;
        
        //执行停车命令
        $this->stopCarService->doStopIn();
        
        //如果停车出错，返回出错信息
        if($this->stopCarService->action_info['code'] < 0){
            return $this->error(1,$this->stopCarService->action_info['message']);
        }
        
        return $this->success('成功停车');
        
        
    }
    
    //出售车辆
    public function sell(MemberRepo $memberRepo,CarRepo $carRepo)
    {
        $unique_car_id = $this->request->car_id;
        $myCar = MyCar::findOrFail($unique_car_id);
        $car_id = $myCar->CarID;
        $car = Car::findOrFail($car_id);
        //检查购买频率
    
        //检查是否已拥有此车
        $my_car = MyCar::where('uid',$this->user->id)->where('CarID',$car_id)->where('ID',$myCar->ID)->first();
        if(!$my_car){
            return $this->error(1,'信息不对称');
        }
        
        $sell_price = $car->getCredit()/2;
        
        $carRepo->countStatus($myCar);
        $surplus_message = '获得';
        if($carRepo->status == config('car.car_status.invalid')){
            //如果车辆还在违停状态，还需要扣除押金
            $sell_price-=$carRepo->forfeit;
        }elseif($carRepo->status <= 3){
            //如果有收益未领取，直接加进卖车价中给用户
            $sell_price+=$carRepo->current_income;
            $surplus_message=sprintf('获得提前收车收益 %s 金币，',$carRepo->current_income).$surplus_message;
        }
        
        //更新车辆状态
        $my_car->delete();
        $record = Record::withoutGlobalScope('status')->where('ParkUid',$this->user->id)->where('myCarID',$myCar->ID)->first();
        if($record){
            $record->delete();
        }
        
        $memberRepo->incrementUserCredit($this->user,$sell_price);
    
        MessageRepo::push([
            'type'=>3,
            'user_id'=>$this->user->id,
            'to_user_id'=>$this->user->id,
            'text'=>sprintf(config('words.messages.sell_car'),$car->CarName),
            'record_id'=>0,
        ]);
        
        return $this->success($surplus_message.sprintf('卖车收益 %s 金币',$sell_price));
    }
    
    //对车辆贴条
    public function punish()
    {
        $unique_car_id = $this->request->car_id;
        $myCar = MyCar::findOrFail($unique_car_id);
        $car_id = $myCar->CarID;
        $owner_id=$this->request->owner_id;
        $car = Car::findOrFail($car_id);//车
        $to_user = Member::findOrFail($owner_id);//车是谁的
    
        $stage = MyStage::where('uid',$owner_id)->where('car_id',$unique_car_id)->whereHas('stage',function($query){
            $query->where('StageType',2);
        })->first();
        if($stage) {
            return $this->error(1,'此车有道具保护，不可被贴条');
        }
    
        $this->stopCarService->user = $this->user;
        $this->stopCarService->car = $car;
        $this->stopCarService->myCar = $myCar;
        $this->stopCarService->to_user = $to_user;
    
        $this->stopCarService->punish();
    
        //如果贴条出错，返回出错信息
        if($this->stopCarService->action_info['code'] < 0){
            return $this->error(1,$this->stopCarService->action_info['message']);
        }
        return $this->success('成功贴条');
    }
    
    
    //收回自己的车辆，并领取收益
    public function backCar(CarRepo $carRepo,MemberRepo $memberRepo)
    {
        $unique_car_id = $this->request->car_id;
        $myCar = MyCar::findOrFail($unique_car_id);
        $car_id = $myCar->CarID;
        $car = Car::findOrFail($car_id);//车
        
        $carRepo->countStatus($myCar);
        
        
        if($carRepo->status <= 3){
    
            $record = Record::where('ParkUid',$this->user->id)->where('myCarID',$unique_car_id)->firstOrFail();
            $parking = Parking::find($record->Parklot);
            
            
            $punishedCredit = $carRepo->current_income?:0;
            
            if($carRepo->status == 3){
                $punisherCredit = floor($carRepo->current_income*config('car.cfgStopLimit.PunisherPersent')/config('car.cfgStopLimit.PunishedPersent'));
                $memberRepo->incrementUserCredit(Member::find($record->ParkWhoUid),$punisherCredit);
                
                MessageRepo::push([
                    'type'=>1,
                    'user_id'=>$this->user->id,
                    'to_user_id'=>$record->ParkWhoUid,
                    'text'=>sprintf(config('words.messages.back_other_car_punished'),$parking->user->nickname,$punisherCredit),
                    'record_id'=>$record->RID,
                ]);
            }
            
            $memberRepo->incrementUserCredit($this->user,$punishedCredit);
            MessageRepo::push([
                'type'=>1,
                'user_id'=>$this->user->id,
                'to_user_id'=>$this->user->id,
                'text'=>sprintf(config('words.messages.back_my_car'),$this->user->nickname,$parking->user->nickname,$punishedCredit),
                'record_id'=>$record->RID,
            ]);
            
            MessageRepo::push([
                'type'=>1,
                'user_id'=>$this->user->id,
                'to_user_id'=>$record->ParkWhoUid,
                'text'=>sprintf(config('words.messages.back_other_car'),
                    $this->user->nickname,
                    $car->CarName,
                    Member::find($record->ParkWhoUid)->nickname,
                    Carbon::parse($record->ParkStartTime)->diffForHumans(null,true),
                    $punishedCredit
                ),
                'record_id'=>$record->RID,
            ]);
    
            //更新记录
            $record->ParkStartTime=Carbon::now()->toDateTimeString();
            $record->ParkStatus=0;
            $record->ParkPunish=0;
            $record->save();
            
            //将此车的所有道具状态改为已使用
            MyStage::where('car_id',$unique_car_id)->update(['status'=>1]);
            
            return $this->success(sprintf('收益（￥%s）已到账',$punishedCredit));
        }
    
        return $this->error(1,'领取失败');
        
        
    }
    
    //缴纳罚金
    public function forfeit(CarRepo $carRepo,MemberRepo $memberRepo)
    {
        $unique_car_id = $this->request->car_id;
        $myCar = MyCar::findOrFail($unique_car_id);
        $car_id = $myCar->CarID;
        $car = Car::findOrFail($car_id);//车
        $carRepo->countStatus($myCar);
    
        if($carRepo->status == 5){
            $credit = $carRepo->forfeit;
    
            //检查用户余额是否足够
            if($this->user->getCredit() < $credit){
                return $this->error(1,'用户余额不足以缴纳罚金');
            }
        
            $memberRepo::decrementUserCredit($this->user,$credit);
        
            $record = Record::withoutGlobalScope('status')->where('ParkUid',$this->user->id)->where('myCarID',$unique_car_id)->first();
        
            if($record){
                $record->ParkStartTime=Carbon::now()->toDateTimeString();
                $record->save();
            }else{
                $record = new Record();
                $record->CarID = $car_id;
                $record->myCarID = $unique_car_id;
                $record->ParkUid = $this->user->id;
                $record->ParkWhoUid = 0;
                $record->Parklot = 0;
                $record->ParkStartTime = Carbon::now()->toDateTimeString();
                $record->ParkStatus=0;
                $record->save();
            }
    
            MessageRepo::push([
                'type'=>1,
                'user_id'=>$this->user->id,
                'to_user_id'=>$this->user->id,
                'text'=>sprintf(config('words.messages.pay_forfeit'),$car->CarName,$credit),
                'record_id'=>$record->RID,
            ]);
            
            $parking_id=$this->request->parking_id;
            if($parking_id){
                if(!MyCar::find($myCar->ID)){
                    return $this->error(1,'车与当前用户信息不对应');
                }
    
                $car = Car::findOrFail($car_id);//停哪辆车
    
                $parking = Parking::findOrFail($parking_id);//停到哪个车位
    
                $to_user = Member::findOrFail($parking->user_id);//车位是谁的
    
                //声明对象准备停车
                $this->stopCarService->user = $this->user;
                $this->stopCarService->car = $car;
                $this->stopCarService->to_user = $to_user;
                $this->stopCarService->parking = $parking;
                $this->stopCarService->myCar = $myCar;
    
                //执行停车命令
                $this->stopCarService->doStopIn();
    
                //如果停车出错，返回出错信息
                if($this->stopCarService->action_info['code'] < 0){
                    return $this->error(1,$this->stopCarService->action_info['message']);
                }
    
                return $this->success('已缴纳罚金并停入车位');
            }
    
            return $this->success('成功缴纳罚金');
        }
    
        return $this->error(1,'缴纳罚金失败');
        
    }
}
